package coms.action;

import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import coms.ejb.sessionbean.*;
import coms.service.BusinessDelegate;
import coms.datatransfer.UserDTO;

public class LoginAction extends ActionSupport implements ModelDriven<UserDTO>{
	
	private UserDTO user;
	private UserBeanRemote userBean;
	private BusinessDelegate delegate;
	
	private static final long serialVersionUID = 1L;
	
    public UserDTO getUser() {return this.user;}
	public void setUser(UserDTO ud) {this.user = ud;}

	public LoginAction(){
		delegate = new BusinessDelegate();
		userBean = (UserBeanRemote) delegate.getBean("userBean");
    }
	
	public String execute() {		
		//HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
		try{
		Map<String,Object> session = ActionContext.getContext().getSession();
		
		if(userBean.validateUser(user)!=null)
		{
			session.put("userID", user.getUserID());
			session.put("firstname", userBean.validateUser(user).getFirstname());
			System.out.println("FirstName:"+userBean.validateUser(user).getFirstname());
			if(userBean.validateUser(user).getRoleDTO().getRoleID()==1){
				return "USERLOGIN";
			}
			
			else if(userBean.validateUser(user).getRoleDTO().getRoleID()==2){
				return "ADMINLOGIN";
			}
			
			else if(userBean.validateUser(user).getRoleDTO().getRoleID()==3){
				return "REVIEWERLOGIN";
			}
			
			addActionMessage("You are valid user!");
			return "success";
		}
		
		return null;
		} catch (Exception e){
			return "exception";
		}
	}
	
	@Override
	public UserDTO getModel() {
		return user;
	}
	
	public String backMethod(){
		return "SUCCESS";
	}
	
	public void validate()
	{
		if(userBean.validateUser(user)==null){			
			addActionError("Your User Name or Password is wrong!");
		}
	}
}
